#include "QbPageOpenHandler.h"
#include <QJsonValue>
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonDocument>
#include <QMetaEnum>
#include "../QbBondModule.h"
#include <QApplication>
#include <include/CmdDefines.h>
#include "qbbond/Detail/BondDetailTab.h"

QbPageOpenHandler::QbPageOpenHandler()
{
}

int QbPageOpenHandler::open_page(const QJsonValue &value, QString &result)
{
    QJsonObject params = value.toArray()[0].toObject();
    const QString& name = params["name"].toString();

    if (name == "show_page_withparam") {
        const int& pageid = params["pageid"].toInt();
        const std::string& param = params["param"].toString().toStdString();
        return QbBondModule::instance().app()->execCommand(pageid, param.c_str());
    }

    if (name == "show_page") {
        const int& pageid = params["pageid"].toInt();
        return QbBondModule::instance().app()->execCommand(pageid, "");
    }

    if (name == "bond_detail_web") {
        const QString& bondkey = params["bondkey"].toString();
        const QString& listmarket = params["listmarket"].toString();
        const int& subpage = params["subpage"].toInt();

        QMetaEnum meta_subpage = QMetaEnum::fromType<BondDetailTab::SUBPAGE_TYPE>();
        const char* key = meta_subpage.valueToKey(subpage);
        if (key == nullptr) {
            result = QString("Invalid subpage value: [%1]").arg(subpage);
            return -1;
        }

        const QString& paraStr = QString("%1.%2|%3").arg(bondkey, listmarket, key);
        return QbBondModule::instance().app()->execCommand(CMD_WebBondDetail_Profile, paraStr.toStdString().c_str());
    }

    // triggerd from 发行人详情 - 发行人概览 - 债券详情 or 发行人详情 - 相关债券
    if (name == "bond_detail") {
        const QString& bondkey = params["bondkey"].toString();
        const QString& listmarket = params["listmarket"].toString();
        const QString& paraStr = QString("%1.%2").arg(bondkey, listmarket);
        return QbBondModule::instance().app()->execCommand(CMD_BondDetail, paraStr.toStdString().c_str());
    }

    const int error_code = QbBondModule::instance().app()->execCommand(&name, &params);
    if (0 != error_code) {
        result = "Failed to exec OpenPage Command";
    }
    return error_code;
}

